package io.github.fb513.transport.util;

import io.github.fb513.transport.model.UserInfo;
import io.github.fb513.transport.model.UserSession;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fengbo
 * @since 2023/12/25 13:59
 */
@Slf4j
public class SessionHolder {

    public static final String SESSION_KEY = "session_key";

    private static final Map<String, UserSession> SESSION_MAP = new ConcurrentHashMap<>();

    public static void save(UserInfo userInfo, NioSocketChannel channel) {
        UserSession userSession = new UserSession();
        userSession.setUserInfo(userInfo);
        userSession.setChannel(channel);
        SESSION_MAP.put(getSessionKey(userInfo), userSession);
    }

    public static String getSessionKey(UserInfo userInfo) {
        return getSessionKey(userInfo.getUserId(), userInfo.getClientType());
    }

    public static String getSessionKey(Long userId, Integer clientType) {
        return userId + "_" + clientType;
    }

    public static UserSession getSession(UserInfo userInfo) {
        return getSession(userInfo.getUserId(), userInfo.getClientType());
    }

    public static UserSession getSession(Long userId, Integer clientType) {
        return getSession(getSessionKey(userId, clientType));
    }

    public static UserSession getSession(String key) {
        return SESSION_MAP.get(key);
    }

    public static void remove(UserInfo userInfo) {
        SESSION_MAP.remove(getSessionKey(userInfo));
    }

    public static UserSession getSession(ChannelHandlerContext ctx) {
        Attribute<String> sessionKey = ctx.channel().attr(AttributeKey.valueOf(SessionHolder.SESSION_KEY));
        if (sessionKey == null || sessionKey.get() == null) {
            log.warn("====================sessionKey is null====================");
            return null;
        }
        UserSession session = SessionHolder.getSession(sessionKey.get());
        if (session == null) {
            log.warn("====================session is null====================");
            return null;
        }
        return session;
    }
}
